package com.iqunxing.redis.redisInAction.ch08.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;
import com.iqunxing.redis.redisInAction.ch08.po.User;
import com.iqunxing.redis.redisInAction.ch08.po.UserMessage;

@Service
public class UserMessageServiceImpl implements UserMessageService {

    private static final Logger logger = LoggerFactory.getLogger(UserMessageServiceImpl.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Long createUserMessage(Long userId, String message) {
        User user = (User) redisTemplate.boundHashOps("user").get(userId);
        Preconditions.checkNotNull(user, "用户不存在");
        logger.info("获取到的用户信息：{}", user);
        Long id = redisTemplate.boundHashOps("id").increment("messageId", 1L);
        UserMessage um = new UserMessage(id, userId, user.getLoginName(), message);
        redisTemplate.boundHashOps("userMessage:" + userId).put(id, um);
        user.setPosts(user.getPosts() + 1);
        redisTemplate.boundHashOps("user").put(user.getId(), user);
        return id;
    }

}
